document.addEventListener('DOMContentLoaded', function() {
    // 应用本地化
    const elements = document.querySelectorAll('[data-i18n]');
    elements.forEach(element => {
        const messageName = element.getAttribute('data-i18n');
        element.textContent = chrome.i18n.getMessage(messageName);
    });

    // 导出所有书签网址并显示在列表中
    document.getElementById('exportBtn').addEventListener('click', function() {
        chrome.bookmarks.getTree(function(bookmarkTreeNodes) {
            let bookmarkList = document.getElementById('bookmarkList');
            bookmarkList.innerHTML = ''; // 清空列表
            processBookmarks(bookmarkTreeNodes, bookmarkList);
        });
    });

    // 导出书签为 CSV 文件
    document.getElementById('exportCSVBtn').addEventListener('click', exportBookmarksAsCSV);

    // 导出历史记录为 CSV 文件
    document.getElementById('exportHistoryBtn').addEventListener('click', exportHistoryAsCSV);
});

// 递归遍历书签树，将书签显示在列表中
function processBookmarks(bookmarks, parentElement) {
    for (let bookmark of bookmarks) {
        if (bookmark.url) {
            let li = document.createElement('li');
            let a = document.createElement('a');
            a.href = bookmark.url;
            a.textContent = bookmark.title || bookmark.url;
            a.target = '_blank';
            li.appendChild(a);
            parentElement.appendChild(li);
        }
        if (bookmark.children) {
            processBookmarks(bookmark.children, parentElement);
        }
    }
}

// 导出书签为 CSV 文件的函数
function exportBookmarksAsCSV() {
    chrome.bookmarks.getTree(function(bookmarkTreeNodes) {
        let rows = [];
        // 添加 CSV 的表头
        rows.push([chrome.i18n.getMessage('csvTitle'),
            chrome.i18n.getMessage('csvUrl'),
            chrome.i18n.getMessage('csvFolderPath'),
            chrome.i18n.getMessage('csvDateAdded')
        ].join(','));
        collectBookmarkData(bookmarkTreeNodes, rows, '');
        let csvContent = rows.join('\n');
        let blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        let url = URL.createObjectURL(blob);
        let link = document.createElement('a');
        let currentDate = new Date().toISOString().slice(0, 10);
        link.download = `Bookmarks_${currentDate}.csv`;
        link.href = url;
        link.style.display = 'none';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    });
}

// 递归遍历书签树，收集书签数据
function collectBookmarkData(bookmarks, rows, parentFolder) {
    for (let bookmark of bookmarks) {
        // 更新当前的文件夹路径
        let currentFolder = parentFolder;
        if (bookmark.title && !bookmark.url) {
            // 这是一个文件夹，更新路径
            currentFolder = parentFolder ? parentFolder + '/' + bookmark.title : bookmark.title;
        }

        if (bookmark.url) {
            let title = '"' + (bookmark.title.replace(/"/g, '""') || '') + '"';
            let url = '"' + bookmark.url.replace(/"/g, '""') + '"';
            let dateAdded = bookmark.dateAdded ? new Date(bookmark.dateAdded).toLocaleString() : '';
            let folderPath = '"' + (currentFolder.replace(/"/g, '""') || '') + '"';
            let row = [title, url, folderPath, dateAdded].join(',');
            rows.push(row);
        }

        if (bookmark.children) {
            collectBookmarkData(bookmark.children, rows, currentFolder);
        }
    }
}

// 导出历史记录为 CSV 文件的函数
function exportHistoryAsCSV() {
    // 获取最近 30 天的历史记录，你可以根据需要调整时间范围
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

    chrome.history.search({
        text: '',
        startTime: thirtyDaysAgo.getTime(),
        maxResults: 10000 // 最大结果数
    }, function(historyItems) {
        let rows = [];
        // 添加 CSV 的表头
        rows.push([chrome.i18n.getMessage('csvTitle'),
            chrome.i18n.getMessage('csvUrl'),
            chrome.i18n.getMessage('csvVisitCount'),
            chrome.i18n.getMessage('csvLastVisitTime')
        ].join(','));

        historyItems.forEach(function(item) {
            let title = '"' + (item.title.replace(/"/g, '""') || '') + '"';
            let url = '"' + item.url.replace(/"/g, '""') + '"';
            let visitCount = item.visitCount || 0;
            let lastVisitTime = item.lastVisitTime ? new Date(item.lastVisitTime).toLocaleString() : '';
            let row = [title, url, visitCount, lastVisitTime].join(',');
            rows.push(row);
        });

        let csvContent = rows.join('\n');
        let blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        let url = URL.createObjectURL(blob);
        let link = document.createElement('a');
        let currentDate = new Date().toISOString().slice(0, 10);
        link.download = `History_${currentDate}.csv`;
        link.href = url;
        link.style.display = 'none';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    });
}